package com.sskj.hangqing.ui.fragment;


import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.formatter.DateFormatter;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.Stock;
import com.sskj.hangqing.bean.rxbus.MarketCoinBean;
import com.sskj.hangqing.presenter.ChartFragmentPresenter;
import com.sskj.hangqing.util.DataUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.ImageUtil;
import com.sskj.lib.util.TimeFormatUtil;
import com.sskj.lib.widget.KChartMorePop;
import com.sskj.lib.widget.KChartPop;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

@Route(path = RConfig.HANG_FRAGMENT_CHART)
public class ChartFragment extends BaseFragment<ChartFragmentPresenter> {

    private boolean isFirst = true;

    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_chart;
    }

    String[] goodsType = {"minute", "minute", "minute5", "minute15", "minute30", "day", "minute60", "hour4", "week", "month"};

    private boolean isUpToggle = true;
    private boolean isDownToggle = false;
    private KChartPop kChartPop;
    private KChartMorePop kChartMorePop;

    @Override
    public ChartFragmentPresenter getPresenter() {
        return new ChartFragmentPresenter();
    }

    @BindView(R2.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R2.id.tvIndicator)
    TextView tvIndicator;
    @BindView(R2.id.tvMore)
    TextView tvMore;
    @BindView(R2.id.llMore)
    LinearLayout llMore;
    @BindView(R2.id.kChartView)
    KChartView kChartView;
    private KChartAdapter mAdapter;
    @Autowired
    String code;
    @Autowired
    String goodType;
    @Autowired
    boolean isBibi;
    @Autowired
    boolean isCandle = true;

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        ArrayList<CustomTabEntity> customTabEntities = new ArrayList<>();
        customTabEntities.add(new TabItem(getString(R.string.hangqingchartFragment1), 0, 0));
        customTabEntities.add(new TabItem("1M", 0, 0));
        customTabEntities.add(new TabItem("5M", 0, 0));
        customTabEntities.add(new TabItem("15M", 0, 0));
        customTabEntities.add(new TabItem("30M", 0, 0));
        customTabEntities.add(new TabItem(getString(R.string.hangqingchartFragment2), 0, 0));
        customTabEntities.add(new TabItem("", 0, 0));
        commonTabLayout.setTabData(customTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                tabSelect(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        initKChart();
        showKLoading();
        mPresenter.getKData(goodType, code, isBibi);
    }

    @Override
    protected void initData() {
        LiveDataBus.get().with(isBibi ? RxBusCode.PUSH_COIN_BEAN_BIBI : RxBusCode.PUSH_COIN_BEAN_LEVEL, CoinBean.class)
                .observe(this, this::refreshCoin);
        LiveDataBus.get().with(RxBusCode.CHANGE_MARKET_CODE, MarketCoinBean.class)
                .observe(this, this::changeCoin);
        mPresenter.initWebSocket(code, goodsType[0], isBibi);
    }

    private void tabSelect(int position) {
        showKLoading();
        if (position != 6) {
            goodType = goodsType[position];
        }
        if (position == 0) {
            kChartView.setDrawMinuteStyle(true);
        } else {
            kChartView.setDrawMinuteStyle(false);
        }
        if (position < 6) {
            tvMore.setText(getString(R.string.hangqingchartFragment3));
        }
        mPresenter.getKData(goodType, code, isBibi);
        mPresenter.initWebSocket(code, goodType, isBibi);
    }

    public void showKLoading() {
        mPresenter.cancelRequest();
        if (kChartView != null) {
            kChartView.showLoading();
        }
    }

    public void hideKLoading() {
        if (kChartView != null) {
            kChartView.refreshComplete();
        }
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(200, llMore, () -> {
            if (kChartMorePop == null) {
                kChartMorePop = new KChartMorePop(getActivity());
                View contentView = kChartMorePop.getContentView();
                View tvFive = contentView.findViewById(R.id.tvFive);
                View tvThirty = contentView.findViewById(R.id.tvThirty);
                View tvWeek = contentView.findViewById(R.id.tvWeek);
                View tvMonth = contentView.findViewById(R.id.tvMonth);

                ClickUtil.click(tvFive, () -> {
                    goodType = goodsType[6];

                    commonTabLayout.setCurrentTab(6);
                    tabSelect(6);

                    tvMore.setText("1H");
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvThirty, () -> {
                    goodType = goodsType[7];
                    tabSelect(7);

                    commonTabLayout.setCurrentTab(6);
                    tvMore.setText("4H");
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvWeek, () -> {
                    goodType = goodsType[8];
                    tabSelect(8);

                    commonTabLayout.setCurrentTab(6);
                    tvMore.setText(getString(R.string.hangqingchartFragment4));
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvMonth, () -> {
                    goodType = goodsType[9];
                    tabSelect(9);

                    commonTabLayout.setCurrentTab(6);
                    tvMore.setText(getString(R.string.hangqingchartFragment5));
                    kChartMorePop.dismiss();
                });
                kChartMorePop.setBackground(0);
            }
            if (kChartMorePop.isShowing()) {
                kChartMorePop.dismiss();
            } else {
                kChartMorePop.showPopupWindow(commonTabLayout);
            }
        });
        try {
            ClickUtil.click(200, tvIndicator, () -> {
                if (kChartPop == null) {
                    kChartPop = new KChartPop(getActivity());
                    View contentView = kChartPop.getContentView();

                    ImageView ivUpToggle = contentView.findViewById(R.id.ivUpToggle);
                    ImageView ivDownToggle = contentView.findViewById(R.id.ivDownToggle);
                    RadioGroup rgMain = contentView.findViewById(R.id.rgMain);
                    RadioGroup rgBottom = contentView.findViewById(R.id.rgBottom);
                    ivUpToggle.setImageResource(R.mipmap.hang_icon_show);
                    ivDownToggle.setImageResource(R.mipmap.hang_icon_hide);
                    rgMain.setOnCheckedChangeListener((group, checkedId) -> {
                        ivUpToggle.setImageResource(R.mipmap.hang_icon_show);
                        kChartPop.dismiss();
                        if (checkedId == R.id.rbMA) {
                            kChartView.setMainDrawMaShow();
                        } else if (checkedId == R.id.rbBOLL) {
                            kChartView.setMainDrawBollShow();
                        }
                    });
                    rgBottom.setOnCheckedChangeListener((group, checkedId) -> {
                        kChartPop.dismiss();
                        if (checkedId == R.id.rbMACD) {
                            kChartView.changeMACD();
                        } else if (checkedId == R.id.rbKDJ) {
                            kChartView.changeKDJ();
                        } else if (checkedId == R.id.rbRSI) {
                            kChartView.changeRSI();
                        } else if (checkedId == R.id.rbWR) {
                            kChartView.changeWR();
                        }
                    });
                    ClickUtil.click(ivUpToggle, () -> {
                        if (isUpToggle) {
                            isUpToggle = false;
                            ivUpToggle.setImageResource(R.mipmap.hang_icon_hide);

                            kChartView.setMainDrawNoneShow();
                        } else {
                            isUpToggle = true;
                            ivUpToggle.setImageResource(R.mipmap.hang_icon_show);
                            kChartView.setMainDrawMaShow();
                        }
                        kChartPop.dismiss();
                    });
                    ClickUtil.click(ivDownToggle, () -> {
                        if (isDownToggle) {
                            isDownToggle = false;
                            ivDownToggle.setImageResource(R.mipmap.hang_icon_hide);

                            kChartView.setDrawDown(isDownToggle);
                        } else {
                            isDownToggle = true;
                            ivDownToggle.setImageResource(R.mipmap.hang_icon_show);

                            kChartView.setDrawDown(isDownToggle);
                        }
                        kChartPop.dismiss();

                    });
                    kChartPop.setBackground(0);
                }
                if (kChartPop.isShowing()) {
                    kChartPop.dismiss();
                } else {
                    kChartPop.showPopupWindow(commonTabLayout);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initKChart() {
        View view = getLayoutInflater().inflate(R.layout.lib_mvc_loading_view, null, false);
        RelativeLayout frameLayoutLoading = view.findViewById(R.id.frameLayoutLoading);
        ImageView ivLoading = view.findViewById(R.id.ivLoading);
        TextView loadingText = view.findViewById(R.id.loadingText);
        loadingText.setVisibility(View.GONE);
        frameLayoutLoading.setBackgroundColor(ContextCompat.getColor(App.INSTANCE, R.color.hangBg));
        ImageUtil.setImage(R.mipmap.lib_loading, ivLoading);
        kChartView.setDrawDownBaseLineZoreUp(false);
        kChartView.setProgressView(view);
        kChartView.showLoading();
        kChartView.setVolumeMaGone(false);
        kChartView.setDrawTabView(false);
        kChartView.setGridRows(3);
        kChartView.setRedUpAndGreenDown(false);
        kChartView.setGridColumns(4);
        kChartView.setMinuteLineWidth(4);
        kChartView.setDrawDown(false);
        kChartView.setPointWidth(RudenessScreenHelper.dp2px(App.INSTANCE, 7));
        kChartView.setGridLineColor(Color.TRANSPARENT);
        kChartView.getmCurrentPricePaint().setTextSize(30);
        kChartView.getmLabelPaint().setColor(ContextCompat.getColor(App.INSTANCE, R.color.libApp));
        kChartView.setShader(Color.parseColor("#306185e5"), Color.parseColor("#106185e5"), Color.parseColor("#026185e5"), 1000);
        kChartView.getmCurrentLinePaint().setColor(getResources().getColor(com.sskj.lib.R.color.libApp));
        kChartView.getmCurrentLinePaint().setPathEffect(null);
        kChartView.getmCurrentPricePaint().setColor(getResources().getColor(com.sskj.lib.R.color.libApp));
        kChartView.setBreathColor(getResources().getColor(com.sskj.lib.R.color.libApp));
        kChartView.setValueFormatter(v ->
                new BigDecimal(CoinUtil.keepCoinPrice(code, v + "")).setScale(CoinUtil.getPriceKeepNum(code), RoundingMode.DOWN).toPlainString()

        );
        if (!isCandle) {
            kChartView.setDrawMinuteStyle(true);
        } else {
        }
        kChartView.setDateTimeFormatter(new DateFormatter() {
            @Override
            public String format(Date date) {
                return TimeFormatUtil.SF_FORMAT_G.format(date);
            }
        });
        kChartView.getmVolumeDraw().setValueFormatter(v ->
                new BigDecimal(CoinUtil.keepCoinNum(code, v + "")).setScale(CoinUtil.getNumKeepNum(code), RoundingMode.DOWN).toPlainString()
        );
        mAdapter = new KChartAdapter();
        kChartView.setAdapter(mAdapter);
    }


    public void setChart(List<Stock> stockList) {

        if (kChartView != null) {
            kChartView.hideLoading();
            if (stockList == null) {
                stockList = new ArrayList<>();
            }
            Collections.reverse(stockList);
            DataUtil.calculate(stockList);
            mAdapter.getDatas().clear();
            mAdapter.updateData(stockList);
        }
    }


    public void changeCoin(MarketCoinBean marketCoinBean) {
        code = marketCoinBean.getCode();
        if (mPresenter != null) {
            mPresenter.getKData(goodType, code, isBibi);
        }
    }

    public void refreshCoin(CoinBean data) {
        if (data.getCode().equals(code) && mAdapter.getCount() > 0) {
            if (isLastNewData(data)) {
                Stock stock = mAdapter.getDatas().get(mAdapter.getCount() - 1);
                stock.setLowestPrice(Math.min(Float.valueOf(stock.getLowestPrice()), Float.valueOf(data.getPrice())) + "");
                stock.setHighestPrice(Math.max(Float.valueOf(stock.getHighestPrice()), Float.valueOf(data.getPrice())) + "");
                stock.setClosePrice(Float.valueOf(data.getPrice()));

                mAdapter.changeLastItemClosePrice(new BigDecimal(data.getPrice()).floatValue());
            } else {
//                mPresenter.getKData(goodType, code, isBibi);

                Stock stock = new Stock();
                stock.setClosePrice(Float.valueOf(data.getPrice()));
                stock.setLowestPrice(data.getPrice());
                stock.setHighestPrice(data.getPrice());
                stock.setOpeningPrice(mAdapter.getDatas().get(mAdapter.getCount() - 1).getClosingPrice());
//                stock.setOpeningPrice(data.getPrice());
//                stock.setVolume(data.getVolume());
                stock.setVolume("0");
                stock.setTimestamp(data.getTimeStamp() - data.getTimeStamp() % getDividerTime());
                mAdapter.getDatas().add(stock);
                DataUtil.calculate(mAdapter.getDatas());
                mAdapter.changeLastItemClosePrice(Float.valueOf(data.getPrice()));
            }
        }
    }

    private boolean isLastNewData(CoinBean data) {

        long compareTime = data.getTimeStamp();
        return isSameTime(compareTime);

    }

    private Long getDividerTime() {
        long dividerTime = 1;
        switch (goodType) {
            case "minute":
                dividerTime = 1000 * 60;
                break;
            case "minute5":
                dividerTime = 1000 * 60 * 5;
                break;
            case "minute15":
                dividerTime = 1000 * 60 * 15;
                break;
            case "minute30":
                dividerTime = 1000 * 60 * 30;
                break;
            case "minute60":
                dividerTime = 1000 * 60 * 60;
                break;
            case "hour4":
                dividerTime = 1000 * 60 * 60 * 4;
                break;
            case "day":
                dividerTime = 1000 * 60 * 60 * 24;
                break;
            case "week":
                dividerTime = 1000 * 60 * 60 * 24 * 7;
                break;
            case "month":
                dividerTime = 1000L * 60L * 60L * 24L * 30L;
                break;
            default:
                break;
        }
        return dividerTime;
    }


    private boolean isSameTime(long compareTime) {
        long dividerTime = 1;
        switch (goodType) {
            case "minute":
                dividerTime = 1000 * 60;
                break;
            case "minute5":
                dividerTime = 1000 * 60 * 5;
                break;
            case "minute15":
                dividerTime = 1000 * 60 * 15;
                break;
            case "minute30":
                dividerTime = 1000 * 60 * 30;
                break;
            case "minute60":
                dividerTime = 1000 * 60 * 60;
                break;
            case "hour4":
                dividerTime = 1000 * 60 * 60 * 4;
                break;
            case "day":
                dividerTime = 1000 * 60 * 60 * 24;
                break;
            case "week":
                dividerTime = 1000 * 60 * 60 * 24 * 7;
                break;
            case "month":
                dividerTime = 1000L * 60L * 60L * 24L * 30L;
                break;
            default:
                break;
        }
        return compareTime / dividerTime <= mAdapter.getDatas().get(mAdapter.getCount() - 1).getDate() / dividerTime;

    }


    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return position >= datas.size() ? datas.get(datas.size() - 1) : datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            return new Date(datas.get(position).getTimestamp());
        }


        /**
         * 向尾部添加数据
         */
        public void updateData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.clear();
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         */
        public void changeLastItemClosePrice(float closePrice) {
            notifyLastItemChanged(closePrice);
        }

    }
}
